﻿using System;
using System.Drawing;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Threading;

namespace monitor_server_2_WPF
{
    /// <summary>
    /// Логика взаимодействия для SplashWindow.xaml
    /// </summary>
    public partial class SplashWindow
    {

        private const int AnimationDurationMs = 0;
        private bool _exitApplication = true;

        public SplashWindow()
        {
            InitializeComponent();
            Loaded += SplashWindow_Loaded;
        }

        private void SplashWindow_Loaded(object sender, RoutedEventArgs routedEventArgs)
        {
            CloseSplashDelegate d = () =>
                {
                    var chk = monitor_2_DBwork.DBwork.CheckConnection();
                    if (!chk)
                    {
                        Dispatcher.Invoke(new CloseSplashDelegate(() =>
                            {
                                Hide();
                                MessageBox.Show(Res.Rm.GetString("NoDBConnection") + ".\r\n" + Res.Rm.GetString("ProgramWillBeClosed") + ".");
                                //ContentLabel.Content = Res.Rm.GetString("NoDBConnection") + ".\r\n" +
                                //               Res.Rm.GetString("ProgramWillBeClosed") + ".";
                                //System.Threading.Thread.Sleep(1000);
                                _exitApplication = true;
                                Close();
                            }));
                    }
                    //System.Threading.Thread.Sleep(500);
                };
            d.BeginInvoke(check_callback, d);
            
            //System.Windows.Media.Brush brush = Background;
            //if (MGrid.Background != System.Windows.Media.Brushes.Transparent && MGrid.Background != null)
            //    brush = MGrid.Background;

            //var scb = (SolidColorBrush)brush;
            //System.Drawing.Color color = System.Drawing.Color.White;
            //if (scb != null)
            //    color = System.Drawing.Color.FromArgb(scb.Color.A, scb.Color.R, scb.Color.G, scb.Color.B);

            //System.Drawing.Brush solidBrush = new SolidBrush(color);

            //
            //var animatedImageControl =
            //    new AnimatedImageControl(this, (Bitmap)Res.Rm.GetObject("cool_loading"), solidBrush);

            //MGrid.Children.Add(animatedImageControl);
        }

        private void check_callback(IAsyncResult ar)
        {
            var state = ar.AsyncState as CloseSplashDelegate;
            if (state != null) state.EndInvoke(ar);
            //CloseSplashDelegate d = (() => Dispatcher.Invoke(new CloseSplashDelegate(CloseThis))); 
            Dispatcher.Invoke(new CloseSplashDelegate(CloseThis));
            
        }

        private void CloseThis()
        {
            MainWindow win = null;
            CloseSplashDelegate d = () =>
                {
                    var a = new DoubleAnimation(1, 0, (new Duration(new TimeSpan(0, 0, 0, 0, AnimationDurationMs))));
                    this.BeginAnimation(OpacityProperty, a);
                    //(MGrid.Children[0] as AnimatedImageControl).Visibility = Visibility.Hidden;
                    CloseSplashDelegate cd = () => System.Threading.Thread.Sleep(AnimationDurationMs);
                    cd.BeginInvoke(ar =>
                        {
                            Dispatcher.Invoke(new CloseSplashDelegate(() =>
                                {
                                    _exitApplication = false;
                                    Close();
                                    win.Show();
                                }));
                        }, cd);
                };

            //(new MainWindow(d)).Show();
            //win = new MainWindow(d);
        }

        private void Window_Closed(object sender, EventArgs e)
        {
            if(_exitApplication)
                Application.Current.Shutdown();
        }
    }

    //public class AnimatedImageControl : UserControl
    //{
    //    delegate void OnFrameChangedDelegate();

    //    readonly System.Drawing.Image _mAnimatedImage;
    //    readonly HwndSource _mHwnd;
    //    Rectangle _mRectangle;
    //    System.Windows.Point _mPoint;
    //    readonly System.Drawing.Brush _mBrush;

    //    public AnimatedImageControl(Window pWindow, Bitmap pBitmap, System.Drawing.Brush pBrush)
    //    {
    //        _mAnimatedImage = pBitmap;
    //        _mHwnd = PresentationSource.FromVisual(pWindow) as HwndSource;
    //        _mBrush = pBrush;
    //        Width = pBitmap.Width;
    //        Height = pBitmap.Height - 6;
    //        //Width = el.ActualWidth;
    //        //Height = el.ActualHeight;
    //        _mPoint = pWindow.PointToScreen(new System.Windows.Point(0, 0));

    //        ImageAnimator.Animate(_mAnimatedImage, OnFrameChanged);

    //        Loaded += AnimatedImageControl_Loaded;
    //    }

    //    void AnimatedImageControl_Loaded(object sender, RoutedEventArgs e)
    //    {
    //        System.Windows.Point point = PointToScreen(new System.Windows.Point(0, 0));
    //        //Перерисовываемая область
    //        _mRectangle = new Rectangle((int)(point.X - _mPoint.X), (int)(point.Y - _mPoint.Y - 6), (int)Width, (int)Height);
    //    }

    //    void OnFrameChangedTs()
    //    {
    //        if(this.Visibility != Visibility.Hidden)
    //            InvalidateVisual();
    //        //DispatcherHelper.DoEvents();
    //    }

    //    void OnFrameChanged(object o, EventArgs e)
    //    {
    //        Dispatcher.BeginInvoke(DispatcherPriority.Normal, new OnFrameChangedDelegate(OnFrameChangedTs));
    //    }

    //    protected override void OnRender(DrawingContext pDrawingContext)
    //    {
    //        //Get the next frame ready for rendering.
    //        ImageAnimator.UpdateFrames(_mAnimatedImage);

    //        //Draw the next frame in the animation.
    //        Graphics gr = Graphics.FromHwnd(_mHwnd.Handle);
    //        gr.FillRectangle(_mBrush, _mRectangle);
    //        gr.DrawImage(_mAnimatedImage, _mRectangle);
    //    }
    //}
}
